package com.settlement.system.service.impl;

import com.settlement.system.common.enums.ChannelEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.RedisUtil;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.mapper.BaseMapper;
import com.settlement.system.mapper.TblBalanceWatcherMapper;
import com.settlement.system.model.entity.common.TblBalanceWatcher;
import com.settlement.system.service.ITblBalanceWatcherService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RR-日记账-余额监控 服务实现类
 *
 * @author Ximi
 * @since 2020-11-17
 */
@Slf4j
@Service
public class TblBalanceWatcherServiceImpl extends BaseServiceImpl implements ITblBalanceWatcherService {

    @Resource
    private TblBalanceWatcherMapper tblBalanceWatcherMapper;

    @Override
    public BaseMapper init() {
        return tblBalanceWatcherMapper;
    }

    /*@Reference(version = "${dubbo.acs.api.version}", timeout = 6000)
    private BalanceWatcherApi balanceWatcherApi;*/

    private static final String ACS_TBL_BALANCE_WATCHER_LOCK = "acs:api:TBL_BALANCE_WATCHER_LOCK";

    @Override
    public TblBalanceWatcher getFoot(Map<String, Object> params) throws ServiceException {
        try {
            return tblBalanceWatcherMapper.getFoot(params);
        } catch (Exception ex) {
            log.error("获取合计异常", ex);
            throw new ServiceException("获取合计异常", ex);
        }
    }

    @Override
    public void refresh(Map<String, Object> model) throws ServiceException {
        try {
            //没有在跑，就调用api,然后等待
            if (!ifRunning()) {
                /*balanceWatcherApi.refresh(model);*/
                int count = 0;
                while (!ifRunning()) {
                    Thread.sleep(1000L);
                    count++;
                    if (count > 10) {
                        return;
                    }
                }
            }
            while (ifRunning()) {
                Thread.sleep(2000L);
            }
        } catch (Exception ex) {
            throw new ServiceException("刷新异常", ex);
        }
    }

    /**
     * 判断是否在跑
     *
     * @return
     */
    boolean ifRunning() {
        long ttl = RedisUtil.getTtl(ACS_TBL_BALANCE_WATCHER_LOCK);
        log.info("ttl={}", ttl);
        if (ttl > 0 || ttl == -1) {
            log.info("已经在刷新，等待跑完");
            return true;
        }
        log.info("没有在跑，等待开始刷新");
        return false;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void save(TblBalanceWatcher originData, TblBalanceWatcher newData) throws ServiceException {
        if (originData != null) {
            newData.setCreateTime(originData.getCreateTime());
            newData.setCreateUser(originData.getCreateUser());
            newData.setId(originData.getId());
            deleteById(originData.getId());
        }
        insert(newData);
    }

    @Override
    public Integer selectOriginBillCount(String channelName, String shopNo, String loginAccount, String outDate) {
        if (ChannelEnum.DY.getName().equals(channelName)) {
            return tblBalanceWatcherMapper.selectDyAccountAmountCount(shopNo, outDate, outDate);
        } else if (ChannelEnum.TM.getName().equals(channelName)) {
            return tblBalanceWatcherMapper.selectTmAccountAmountCount(shopNo, outDate, outDate);
        } else if (ChannelEnum.JD.getName().equals(channelName)) {
            return tblBalanceWatcherMapper.selectJdAccountAmountCount(shopNo, outDate, outDate);
        } else if (ChannelEnum.OR.getName().equals(channelName)) {
            return tblBalanceWatcherMapper.selectOrAccountAmountCount(loginAccount, outDate, outDate);
        }
        return 0;
    }

    @Override
    public Integer selectOriginBillCount(Map<String, Object> map) {
        return selectOriginBillCount((String) map.get("channelName"), (String) map.get("shopNo"), (String) map.get("loginAccount"), (String) map.get("outDate"));
    }

    private void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "ncShopNo", "loginAccount");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveData(List<TblBalanceWatcher> datas) throws ServiceException {
        try {
            for (TblBalanceWatcher data : datas) {
                Map<String, Object> map = new HashMap<String, Object>(16);
                map.put("loginAccount", data.getLoginAccount());
                map.put("channelName", data.getChannelName());
                map.put("shopNo", data.getShopNo());
                map.put("isStartItem", "Y");
                setParamsModel(map);
                TblBalanceWatcher watcher = null;
                List<TblBalanceWatcher> watchers = selectByParam(map);
                if (watchers != null && !watchers.isEmpty()) {
                    watcher = watchers.get(0);
                }
                SystemUserUtil.setDefualt(data);
                if (watcher != null) {
                    data.setCreateTime(watcher.getCreateTime());
                    data.setCreateUser(watcher.getCreateUser());
                    data.setId(watcher.getId());
                    deleteById(watcher);
                }
                insert(data);
            }
        } catch (Exception ex) {
            log.error("导入数据异常", ex);
            throw new ServiceException("导入数据异常", ex);
        }
    }
}

